
import cv2
import logging
import numpy as np


logging.basicConfig(level = logging.INFO,format = '%(asctime)s %(levelname)s %(name)s %(funcName)s(%(lineno)d):%(message)s')
logger = logging.getLogger(__name__)


def drawTempAndImg(tempimg, img):
    h0, w0, d = tempimg.shape
    h1, w1, d1 = img.shape
    ddtype = type(tempimg[0, 0, 0])

    img0 = np.zeros((max(h0, h1), w0 + w1, d), dtype=ddtype)

    #logger.info(tempimg.shape)
    #logger.info(img.shape)
    #logger.info(img0.shape)

    img0[:h0, :w0, :] = tempimg
    img0[:h1, w0:, :] = img

    return img0

def checkIsGray(img):
    score = 0
    b, g, r = cv2.split(img)

    res = cv2.absdiff(b, g)
    score += np.mean(res)
    #logger.info("b g score {}".format(score))

    res = cv2.absdiff(b, r)
    score += np.mean(res)
    #logger.info("b r score {}".format(score))

    res = cv2.absdiff(g, r)
    score += np.mean(res)

    return score

def getQueueTitle(img0):

    h, w, d = img0.shape
    img = img0.copy()
    for i in range(h):
        for j in range(w):
            if img0[i, j, 0] > 25 or img0[i, j, 1] < 170 or img0[i, j, 2] < 170:
                img[i][j] = [0, 0, 0]

    return img

def templateMatch(img0, template, name=None, enum=None):
    w, h, d = template.shape
    methods = ['cv2.TM_CCOEFF',
               'cv2.TM_CCOEFF_NORMED',
               'cv2.TM_CCORR',
               'cv2.TM_CCORR_NORMED',
               'cv2.TM_SQDIFF',
               'cv2.TM_SQDIFF_NORMED']
    method = methods[5]
    res = cv2.matchTemplate(img0, template, eval(method))
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in ['cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']:
        top_left = min_loc
    else:
        top_left = max_loc


    imgg = img0[top_left[1]:top_left[1] + w, top_left[0]:top_left[0] + h]

    imgg0 = cv2.absdiff(imgg, template)

    score = np.mean(imgg0)

    logger.info("{} score2 {}".format(name, score))

    return top_left, score



